package com.wing.purchase.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.purchase.model.entity.PurchaseStorageWork;
import com.wing.purchase.model.entity.PurchaseStorageWorkProduct;
import com.wing.purchase.model.request.PurchaseStorageWorkForm;
import com.wing.purchase.model.request.SimpleStorageForm;
import com.wing.purchase.model.response.PurchaseStorageWorkExportVO;
import com.wing.purchase.model.response.PurchaseStorageWorkVO;
import com.wing.purchase.service.PurchaseStorageWorkService;
import com.wing.utils.ExcelUtils;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import com.wing.web.db.config.util.DynamicDataSource;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 采购入库作业
 *
 * @author xiayang
 */
@Validated
@Api(value = "采购入库作业管理", tags = "#/purchase/purchaseStorageWork")
@RestController("purchaseStorageWorkController")
@RequestMapping("purchase/admin/purchaseStorageWork")
@RequiredArgsConstructor
public class PurchaseStorageWorkController {

    private final PurchaseStorageWorkService purchaseStorageWorkService;


    @ApiOperation(value = "查询所有采购入库作业", notes = "搜索")
    @GetMapping("/list")
    public PageResult<PurchaseStorageWorkVO> list(
        @RequestParam(defaultValue = "1") Integer page,
        @RequestParam(defaultValue = "10") Integer limit,
        @RequestParam(defaultValue = "create_time") String sort,
        @RequestParam(defaultValue = "desc") String order,
        String workNo,
        String skuName,
        String skuCode,
        String warehouseShelfSpaceCode,
        String startCreateTime,
        String endCreateTime
    ) {
        Page<PurchaseStorageWorkVO> pg = new Page<>(page, limit);
        Map<String, Object> params = new HashMap<>();
        params.put("workNo", workNo);
        params.put("skuName", skuName);
        params.put("skuCode", skuCode);
        params.put("warehouseShelfSpaceCode", warehouseShelfSpaceCode);
        params.put("startCreateTime", startCreateTime);
        params.put("endCreateTime", endCreateTime);

        Page<PurchaseStorageWorkVO> list = purchaseStorageWorkService.pageList4app(pg, params);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }


    @ApiOperation(value = "添加采购入库作业", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@RequestBody PurchaseStorageWorkForm purchaseStorageWorkForm) {
        try {
            PurchaseStorageWorkProduct purchaseStorageWorkProduct = purchaseStorageWorkForm.getPurchaseStorageWorkProduct();
            if(purchaseStorageWorkProduct.getWarehouseId()==null){
                return JsonResult.fail("请确认仓库是否为空！");
            }
            if(purchaseStorageWorkProduct.getWarehouseAreaId()==null){
                return JsonResult.fail("请确认仓库库区是否为空！");
            }
            if(purchaseStorageWorkProduct.getWarehouseShelfSpaceId()==null){
                return JsonResult.fail("请确认仓库库位是否为空！");
            }
            if(StringUtils.isEmpty(purchaseStorageWorkProduct.getSkuCode())){
                return JsonResult.fail("请确认物料编码是否为空！");
            }
            if(purchaseStorageWorkProduct.getQuantity().compareTo(BigDecimal.ZERO) <= 0){
                return JsonResult.fail("入库数量为空或者为0！");
            }
            if (purchaseStorageWorkService.add(purchaseStorageWorkForm) > 0) {
                return JsonResult.success("添加成功");
            }
            return JsonResult.fail("添加失败");
        } catch (BusinessException e) {
            return JsonResult.fail(e.getCode(), e.getMessage());
        } catch (Exception e) {
            return JsonResult.fail(e.getMessage());
        }
    }


    @ApiOperation(value = "修改采购入库作业", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(PurchaseStorageWorkForm purchaseStorageWorkForm) {
        PurchaseStorageWork purchaseStorageWork = purchaseStorageWorkService.getById(purchaseStorageWorkForm.getId());
        if (purchaseStorageWork == null) {
            return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(PurchaseStorageWork.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(purchaseStorageWorkForm, purchaseStorageWork, copyOptions);
        if (purchaseStorageWorkService.updateById(purchaseStorageWork)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }


    @ApiOperation(value = "删除采购入库作业", notes = "删除")
    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable("id") Long purchaseStorageWorkId) {
        if (purchaseStorageWorkService.removeById(purchaseStorageWorkId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }

    @ApiOperation(value = "简易入库", notes = "简易入库")
    @PostMapping("/simpleStorage")
    public JsonResult simpleStorage(@RequestBody SimpleStorageForm simpleStorageForm) {
       try {
          if(StringUtils.isBlank(simpleStorageForm.getSkuName())){
               return JsonResult.fail("物料名称为空");
           }
          if(StringUtils.isBlank(simpleStorageForm.getSkuCode())){
               return JsonResult.fail("物料编码为空");
           }
           if(simpleStorageForm.getWarehouseId()==null){
               return JsonResult.fail("请确认仓库是否为空！");
           }
           if(simpleStorageForm.getWarehouseAreaId()==null){
               return JsonResult.fail("请确认仓库库区是否为空！");
           }
           if(simpleStorageForm.getWarehouseShelfSpaceId()==null){
               return JsonResult.fail("请确认仓库库位是否为空！");
           }
           if (purchaseStorageWorkService.simpleStorage(simpleStorageForm) > 0) {
                return JsonResult.success("添加成功");
            }
            return JsonResult.fail("添加失败");
        } catch (BusinessException e) {
            return JsonResult.fail(e.getCode(), e.getMessage());
        } catch (Exception e) {
            return JsonResult.fail(e.getMessage());
        }

    }




    @ApiOperation(value = "导出")
    @GetMapping("/export")
    public void export(HttpServletResponse response,
                       @RequestParam(name = "skuCode", required = false) String skuCode,
                       @RequestParam(name = "skuName", required = false) String skuName,
                       @RequestParam(name = "workNo", required = false) String workNo,
                       @RequestParam(name = "warehouseShelfSpaceCode", required = false) String warehouseShelfSpaceCode
    ){
        Page<PurchaseStorageWorkVO> pg = new Page<>(1, 999999);

        List<PurchaseStorageWorkExportVO> list = new ArrayList<>();

        Map params = new HashMap();
        // 搜索
        if (StringUtils.isNotBlank(workNo)) {
            params.put("workNo", workNo);
        }
        if (StringUtils.isNotBlank(skuName)) {
            params.put("skuName", skuName);
        }
        if (StringUtils.isNotBlank(skuCode)) {
            params.put("skuCode", skuCode);
        }
        if (StringUtils.isNotBlank(warehouseShelfSpaceCode)) {
            params.put("warehouseShelfSpaceCode", warehouseShelfSpaceCode);
        }


        String databaseUser = DynamicDataSource.USER_PREFIX;
        if (StringUtils.isNotBlank(DynamicDataSource.name.get())) {
            databaseUser = databaseUser + "-" + DynamicDataSource.name.get();
        }
        params.put("databaseUser", databaseUser);

        list = purchaseStorageWorkService.exportInWorkList4app(pg,params);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        String timestamp = sdf.format(new Date());
        // 生成带时间戳的文件名
        String fileName = "入库作业数据表_" + timestamp;
        ExcelUtils.export(response,fileName,list, PurchaseStorageWorkExportVO.class);
    }
}
